/*
 *  Copyright:  (C) 2018 LingYun IoT System Studio
 *              All rights reserved.
 *
 *  File name:  FileIo.c
 *Description:  Creat or open a file called "test.txt",then write string MSG_STR to this file,
 *              at last,read this file.
 *
 *    Version:  1.1
 *     Author:  Guo Wenxue <guowenxue@gmail.com>
 *		        Copied by Zhu Tianyin <zhuty_cn@163.com>
 *  ChangeLog:  1.0  Release initial version in 2018.
 *              1.1  Copy and change some details on "01/07/2021".
 */
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define BUFSIZE 1024
#define MSG_STR "Hello World\n"

int main(int argc, char **argv)
{
	int fd = -1;
	int rv = -1;
	char buf[BUFSIZE];

	fd = open("test.txt", O_RDWR|O_CREAT|O_TRUNC, 0666);
	if(fd < 0)
	{
		perror("Open/Create file test.txt failure");
		return 0;
	}
	printf("Open file returned file descriptor [%d]\n", fd);

	if( (rv=write(fd, MSG_STR, strlen(MSG_STR)))<0 )
	{
		printf("Write %d bytes into file failure: %s\n", rv, strerror(errno));
		goto cleanup;
	}

	memset(buf, 0, sizeof(buf));                         //Avoid buffer mistake
	lseek(fd, 0, SEEK_SET);                              //Set file offset to read file
	if((rv=read(fd, buf, sizeof(buf)))<0)
	{
		printf("Read data from file failure: %s\n", strerror(errno));
		goto cleanup;
	}
	printf("Read %d bytes data from file: %s\n", rv, buf);

cleanup:
	close(fd);
	return 0;
}
